<template>
  <div
    ref="darg"
    class="_darg"
    draggable="true"
    @dragstart="ondragstart"
    @drag="ondrag"
    :style="style"
  >
    <slot></slot>
  </div>
</template>

<script>
export default {
  props: {
    //是否开启边界回弹
    spring: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      translateX: 0,
      translateY: 0,
      offsetXOnce: 0,
      offsetYOnce: 0,
      baseX: 0,
      baseY: 0,
    };
  },
  computed: {
    style() {
      const { translateX, translateY } = this;
      return `transform: translateX(${translateX}px) translateY(${translateY}px) translateZ(0);`;
    },
  },
  methods: {
    ondragstart(ev) {
      const { clientX, clientY } = ev;
      this.offsetXOnce = clientX;
      this.offsetYOnce = clientY;
      this.baseX = this.translateX;
      this.baseY = this.translateY;
    },
    ondrag(ev) {
      const { clientX, clientY } = ev;
      if (clientX && clientY) {
        this.translateX = this.baseX + clientX - this.offsetXOnce;
        this.translateY = this.baseY + clientY - this.offsetYOnce;
      }
    },
  },
};
</script>

<style scoped>
._darg {
  position: fixed;
  right: 0;
  top: 53%;
  z-index: 1000000;
  touch-action: none;
}
._darg:hover {
  cursor: pointer;
}
</style>